#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
import cgi
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import urlfetch
import urllib # Used to unescape URL parameters.
#import settings

try:
  from xml.etree import ElementTree
except ImportError:
  from elementtree import ElementTree
import gdata.calendar.service#Google data calender
import gdata.service
import atom.service
import gdata.calendar
import atom
import getopt
import sys
import string
import time
#import ssl


class Wnewegg(webapp.RequestHandler):    
#    def __init__(self):
#        self.result={}
#        pass
    def getprice(self,pname):    
        self.result={}
        pname=pname.replace(' ','%20')
        turl='http://www.newegg.com.cn/Search.aspx?keyword='+pname #TLM42V66PK%2042'
    #    cnurl='http://store.apple.com/cn/browse/home/shop_iphone/family/iphone'
        req=urlfetch.fetch(turl,method=urlfetch.GET,headers={},allow_truncated=False,follow_redirects=True)
    #    req.add_header ("Referer","q.stock.sohu.com/cn/zs.shtml")
        content=req.content.decode("gbk")
        tag1='canonical'
        p1=content.find(tag1)
        p2=content.find('http',p1)
        p3=content.find('"',p2)
        turl=content[p2:p3]
        self.result['link']=turl
#        print(content.encode('gbk'))       
        if content.find('十分抱歉'.decode('utf8'))>0:
            self.result['price']=-1
            return self.result
        else:   
            tag4='neweggPrice'
            p4=content.find(tag4)
            tag5='http'
            p5=content.find(tag5,p4)
            tag6='"'
            p6=content.find(tag6,p5)
            price=content[p5:p6]
            print('price',tag4,p4,tag5,p5,p6,price)
#            print('price',price)
            self.result['price']=price
        return self.result
#            print(content)
class W360buy():
    def __init__(self):
        self.result={}

        pass
    def getprice(self,pname):
        pname=pname.replace(' ','%20')
        turl='http://search.360buy.com/Search?keyword='+pname #TLM42V66PK%2042'
    #    cnurl='http://store.apple.com/cn/browse/home/shop_iphone/family/iphone'
        req=urlfetch.fetch(turl,method=urlfetch.GET,headers={},allow_truncated=False,follow_redirects=True)
    #    req.add_header ("Referer","q.stock.sohu.com/cn/zs.shtml")
        content=req.content.decode("gbk")
        tag1='>共<'.decode('utf8')
        p1=content.find(tag1)
        p2=content.find('>',p1+len(tag1))
        p3=content.find('<',p2)
#        print(p1,p2)
#        print(content)
        rnumber=content[p2+1:p3]
#        print(rnumber)
        if rnumber==0  :
            self.result['price']=-1
            return self.result
        else:
            tag4='<div class="p-price">'
            p4=content.find(tag4,p3)
            tag5='http'
            p5=content.find(tag5,p4)

            p6=content.find(tag5,p5+len(tag5)+2)
            if p6>0:
                p7=content.find('png',p6)
                price=content[p6:p7]+'png'
            else:
                p7=content.find('png',p5)
                price=content[p5:p7]+'png'
            self.result['price']=price
          ########################################

            tag8='<div class="p-name">'
            p8=content.find(tag8,p3)
            tag9='href='
            p9=content.find(tag9,p8)
            tag10='"'
            p10=content.find(tag10,p9+len(tag9)+2)
            url2=content[p9+len(tag9)+1:p10]
#            print('line',url2)
            self.result['link']=url2
            return self.result

class Wcoo8():
    def __init__(self):
        self.result={}
    def getprice(self,pname):
        pname=pname.replace(' ','%20')
        turl='http://www.coo8.com/search/search.jsp?k='+pname #TLM42V66PK%2042'
    #    cnurl='http://store.apple.com/cn/browse/home/shop_iphone/family/iphone'
        req=urllib.request.Request (turl)
    #    req.add_header ("Referer","q.stock.sohu.com/cn/zs.shtml")
        page=urllib.request.urlopen(req)
        content=str(page.read().decode("gbk"))  
        tag1='>共<'
        p1=content.find(tag1)
        p2=content.find('>',p1+len(tag1))
        p3=content.find('<',p2)
        
        

class Xshopfinder(webapp.RequestHandler):
    def get(self):
        pname=self.request.get('pname')
        if len(pname)>0:
            self.response.out.write('商品名称:'.decode('utf8') + pname+'<br>')

            buyname= pname#'TLM42V66PK 42'
            #buyname= 'dfsdfsdfsdfsdfsdf'
            self.response.out.write('--------------京东网站价格:------------'.decode('utf8') + pname+'<br>')
            t=W360buy()
            r={}
            r=t.getprice(buyname)
            for e in r.keys():
                if len(r[e])>4:
                    if r[e][:4]=='http':
                        if e=='price':
                            self.response.out.write(e+'=<img src='+r[e]+'><br>')
                        else:
                            self.response.out.write('<a href='+r[e]+'>'+e+'</a><br>')
            self.response.out.write('--------------新蛋网站价格:------------'.decode('utf8') + pname+'<br>')
            r={}
            t=Wnewegg()
            r=t.getprice(buyname)
            for e in r.keys():
                if len(r[e])>4:
                    if r[e][:4]=='http':
                        if e=='price':
                            self.response.out.write(e+'=<img src='+r[e]+'><br>')
                        else:
                            self.response.out.write('<a href='+r[e]+'>'+e+'</a><br>')
#            r={}
#            t=Wsuning()
#            r=t.getprice(buyname)
#            self.response.out.write(r)
            
        self.response.out.write("""
          <form action="/shopfinder" method="get">
            <div><textarea name="pname" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="find cheaper"></div>
          </form>""")

def main():
    application = webapp.WSGIApplication([('/shopfinder', Xshopfinder)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()

